<template>
  <div>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :currentPage="page.currPage"
        :viewFunc="handleView"
        :delFunc="handleDelete"
        :modifyPwdFunc="handleModifyPwd"
        :change-page="changePage"
        :editFunc="handleEdit"
      >
        <template #toolbarBtn>
          <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd"
            >新增</el-button
          >
        </template>
        <!-- 用户状态 -->
        <template #userStatus="{ rows }">
          <el-tag type="success" v-if="rows.userStatus === 1">启用</el-tag>
          <el-tag type="danger" v-else>停用</el-tag>
        </template>
      </TableCustom>
    </div>
    <el-dialog
      :title="isEdit ? '编辑' : '新增'"
      v-model="visible"
      width="700px"
      destroy-on-close
      :close-on-click-modal="closeDialog"
      @close="closeDialog"
    >
      <TableEdit
        :form-data="rowData"
        :options="options"
        :edit="isEdit"
        :update="updateData"
        @closeDialogP="closeDialog"
      />
    </el-dialog>
    <el-dialog title="详情" v-model="visible1" width="700px" destroy-on-close>
      <TableDetail
        :data="viewData"
        @closeDialogP="visible1 = false"
      ></TableDetail>
    </el-dialog>
    <!-- 修改密码 -->
    <el-dialog
      title="修改密码"
      v-model="visible2"
      width="700px"
      destroy-on-close
    >
      <el-form-item label="新密码">
        <el-input placeholder="" v-model="modifyForm.password"></el-input>
      </el-form-item>
      <el-button type="primary" @click="modifyBtn">保 存</el-button>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="system-user">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { CirclePlusFilled } from "@element-plus/icons-vue";
import { User } from "@/types/user";
import {
  fetchAccoutListData,
  fetchRoleSelect,
  fetchAccoutCreate,
  fetchDeleteAccout,
  fetchModifyPassword,
} from "@/api/accountManage";
import TableCustom from "@/components/table-custom.vue";
import TableDetail from "@/components/table-detail.vue";
import TableSearch from "@/components/table-search.vue";
import { FormOption, FormOptionList } from "@/types/form-option";

// 查询相关
const query = reactive({
  keyword: "",
});
const searchOpt = ref<FormOptionList[]>([
  { type: "input", label: "用户名：", prop: "keyword", placeholder:'请输入用户名' },
]);
const handleSearch = () => {
  changePage(1);
};

const roleList = ref([]);
// 获取角色下拉框
const getRoleSelect = async () => {
  const res = await fetchRoleSelect({});
  console.log("获取角色下拉框");
  console.log(res.data);
  let list = res.data.data;
  list.forEach((item) => {
    item.label = item.value;
    item.value = item.id;
  });
  options.value.list[3].opts = list;
  roleList.value = list;
};
getRoleSelect();

// 表格相关
let columns = ref([
  { type: "index", label: "序号", width: 55, align: "center" },
  { prop: "userName", label: "用户名" },
  { prop: "roleName", label: "角色名" },
  { prop: "userStatus", label: "状态" }, //状态 0-停用 1-启用
  { prop: "createTime", label: "创建时间" },
  { prop: "operator", label: "操作", width: 300, fixed: "right" },
]);
const page = reactive({
  currPage: 1,
  size: 10,
  total: 0,
});
const tableData = ref([]);
const getData = async () => {
  let params = {
    currPage: page.currPage,
    size: page.size,
    keyword: query.keyword,
    userType: 1, //用户类型 1-管理员 2-游客(用户端用户)
  };
  const res = await fetchAccoutListData(params);

  let list = res.data.data.records;

  list.forEach((item, index) => {
    let roleName = [];
    item.roleId.forEach((item2, index2) => {
      roleList.value.forEach((item3, index4) => {
        if (item2 === item3.id) {
          roleName.push(item3.label);
          item.roleName = roleName.join("，");
        }
      });
    });
  });
  tableData.value = list;
  console.log("账号列表");
  console.log(tableData.value);
  page.total = res.data.data.total;
  console.log(page.total);
};
getData();

// 分页
const changePage = (val: number) => {
  console.log("点击分页---歌单分类管理");
  page.currPage = val;
  console.log(page.currPage);
  getData();
};

// 新增/编辑弹窗相关
let options = ref<FormOption>({
  labelWidth: "100px",
  span: 24,
  list: [
    { type: "input", label: "用户名", prop: "userName", required: true, placeholder:'请输入用户名' },
    { type: "input", label: "手机号", prop: "phone", required: true, placeholder:'请输入手机号' },
    { type: "input", label: "密码", prop: "password", required: true, placeholder:'请输入密码' },
    {
      type: "select",
      label: "角色名",
      prop: "roleId",
      multiple: true,
      opts: [],
      placeholder:'请选择角色名'
    },
  ],
});

const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});

// 新增
const handleAdd = (row) => {
  console.log("新增");
  rowData.value = { ...row };
  isEdit.value = false;
  visible.value = true;
};

// 编辑
const handleEdit = (row) => {
  console.log("编辑");
  rowData.value = { ...row };
  isEdit.value = true;
  visible.value = true;
};
const updateData = async (data) => {
  let datas = {};
  let obj = {};
  let editObi = { roleId: data.roleId };
  if (isEdit.value) {
    datas = { ...data, ...obj, ...editObi };
  } else {
    datas = { ...data, ...obj };
  }

  console.log("最终编辑或者新增的数据---是");
  console.log(datas);
  const res = await fetchAccoutCreate(datas);
  console.log("新增歌单分类");
  console.log(res.data);
  closeDialog();
  getData();
};

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
};

// 详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: [],
});
const handleView = (row) => {
  viewData.value.row = { ...row };
  viewData.value.list = [
    {
      prop: "userName",
      label: "用户名",
    },
    {
      prop: "phone",
      label: "手机号",
    },
    {
      prop: "roleName",
      label: "角色名",
    },
    {
      prop: "createTime",
      label: "创建时间",
    },
  ];
  visible1.value = true;
};

// 删除相关
const handleDelete = async (row) => {
  console.log("删除");
  console.log(row);
  let datas = {
    id: row.userId,
  };
  const res = await fetchDeleteAccout(datas);
  if (res.data.code == 0) {
    ElMessage.success("删除成功");
    getData();
  }
};

const visible2 = ref(false);
const selectRow = ref({
  userId: "",
});
const modifyForm = ref({
  password: "",
});
// 修改密码
const handleModifyPwd = async (row) => {
  console.log("点击--修改密码");
  console.log(row);
  selectRow.value = row;
  visible2.value = true;
  modifyForm.value.password = "";
};
const modifyBtn = async (row) => {
  console.log("点击--修改密码---保存");
  console.log(selectRow.value);
  if (modifyForm.value.password.trim() === "") {
    ElMessage.warning("密码不能为空");
    return;
  }
  const res = await fetchModifyPassword({
    password: modifyForm.value.password,
    userId: selectRow.value.userId,
  });
  if (res.data.code == 0) {
    ElMessage.success("修改成功");
  } else {
    ElMessage.error(res.data.msg);
  }
  visible2.value = false;
};
</script>

<style scoped></style>
